<template>
  <el-dialog
    :model-value="dialogVisible"
    :title="isEditMode ? '编辑合同' : '新建合同'"
    width="600px"
    @close="handleDialogClose"
  >
    <el-form ref="contractFormRef" :model="contractForm" :rules="contractRules" class="dialog-form">
      <el-descriptions :column="1" border class="custom-descriptions">
        <el-descriptions-item>
          <template #label>
            <span class="required-label">合同名称</span>
          </template>
          <el-form-item prop="coName" required style="margin-top: 16px">
            <el-input
              v-model="contractForm.coName"
              placeholder="请输入"
              :maxlength="128"
              show-word-limit
              style="width: 100%"
              :disabled="
                isEditMode &&
                currentContract?.crType === '工程类' &&
                currentContract?.children &&
                currentContract.children.length > 0
              "
            />
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <span class="required-label">合同类型</span>
          </template>
          <el-form-item prop="crType" required style="margin-top: 16px">
            <el-radio-group v-model="contractForm.crType">
              <el-radio v-for="item in ctypeOptions" :key="item.value" :label="item.value">{{
                item.label
              }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-descriptions-item>
        <!-- 工程类特有字段 -->
        <el-descriptions-item v-if="contractForm.crType === 1">
          <template #label>
            <span class="required-label">工程名称</span>
          </template>
          <el-form-item prop="projectName" required style="margin-top: 16px">
            <el-input
              v-model="contractForm.projectName"
              placeholder="请输入"
              :maxlength="128"
              show-word-limit
              style="width: 100%"
              :disabled="
                isEditMode &&
                currentContract?.crType === 1 &&
                currentContract?.children &&
                currentContract.children.length > 0
              "
            />
          </el-form-item>
        </el-descriptions-item>

        <!-- 直销类特有字段 -->
        <el-descriptions-item v-if="contractForm.crType === 2">
          <template #label>
            <span class="required-label">关联需求</span>
          </template>
          <el-form-item prop="requirementId" required style="margin-top: 16px">
            <el-select
              v-model="contractForm.requirementId"
              placeholder="请选择"
              filterable
              style="width: 100%"
              @change="handleRequirementChange"
            >
              <el-option
                v-for="item in requirementOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-descriptions-item>

        <!-- 需求编号 -->
        <el-descriptions-item v-if="contractForm.crType === 2" label="需求编号">
          <el-form-item style="margin-top: 16px">
            <el-input v-model="contractForm.deId" placeholder="" disabled style="width: 100%" />
          </el-form-item>
        </el-descriptions-item>
      </el-descriptions>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleDialogClose">取消</el-button>
        <el-button type="primary" @click="handleDialogSubmit">{{
          isEditMode ? '保存' : '确定'
        }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup name="createModal">
import { ref, reactive, watch, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { submitCreateContract } from '@/api/business/contract'

// 定义props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  isEdit: {
    type: Boolean,
    default: false
  },
  contractData: {
    type: Object,
    default: () => ({})
  },
  ctypeOptions: {
    type: Array,
    default: () => []
  },
  requirementOptions: {
    type: Array,
    default: () => []
  }
})

// 定义emits
const emit = defineEmits(['update:visible', 'close', 'submit'])

// 表单引用
const contractFormRef = ref(null)

// 新建合同表单数据
const contractForm = reactive({
  coName: '',
  crType: 1, // 默认为工程类
  contractNo: '', // 合同编号
  projectName: '', // 工程类字段
  requirementId: '', // 直销类字段
  deId: undefined // 需求编号
})

// 当前编辑的合同
const currentContract = ref(null)

// 监听props变化，更新内部状态
watch(
  () => props.visible,
  (newVal) => {
    dialogVisible.value = newVal
    // 当弹窗打开时，确保正确设置编辑模式和数据
    if (newVal) {
      isEditMode.value = props.isEdit
      // 立即更新表单数据
      updateFormData()
    }
  }
)

watch(
  () => props.isEdit,
  (newVal) => {
    isEditMode.value = newVal
    // 当编辑模式改变时，更新表单数据
    updateFormData()
  }
)

watch(
  () => props.contractData,
  () => {
    // 当合同数据改变时，更新表单数据
    updateFormData()
  },
  { deep: true }
)

// 更新表单数据的函数
function updateFormData() {
  const newVal = props.contractData
  if (newVal) {
    currentContract.value = newVal
    // 无论是否为编辑模式，都更新表单数据，以便在弹窗打开时能正确显示
    contractForm.coName = newVal.coName || ''
    contractForm.crType = newVal.crType || 1
    contractForm.contractNo = newVal.contractNo || ''

    if (newVal.crType === 1) {
      contractForm.projectName = newVal.projectName || ''
    } else if (newVal.crType === 2) {
      // 对于直销类合同，查找对应的需求ID
      const requirement = props.requirementOptions.find((item) => item.deId === newVal.deId)
      if (requirement) {
        contractForm.requirementId = requirement.value
        contractForm.deId = requirement.deId
      }
    }
  }
}

// 内部状态
const dialogVisible = ref(false)
const isEditMode = ref(false)

// 表单验证规则
const contractRules = {
  coName: [
    { required: true, message: '请输入合同名称', trigger: 'blur' },
    { min: 1, max: 128, message: '合同名称长度在 1 到 128 个字符', trigger: 'blur' }
  ],
  crType: [{ required: true, message: '请选择合同类型', trigger: 'change' }],
  projectName: [
    { required: true, min: 1, max: 128, message: '工程名称长度在 1 到 128 个字符', trigger: 'blur' }
  ],
  requirementId: [
    {
      required: (rule, value, callback) => {
        if (contractForm.crType === 2 && !value) {
          callback(new Error('请选择关联需求'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
}

// 处理需求变更
function handleRequirementChange(value) {
  const requirement = props.requirementOptions.find((item) => item.value === value)
  if (requirement) {
    contractForm.deId = requirement.deId
  } else {
    contractForm.deId = ''
  }
}

// 重置表单
function resetForm() {
  contractForm.coName = ''
  contractForm.crType = 1
  contractForm.contractNo = ''
  contractForm.projectName = ''
  contractForm.requirementId = ''
  contractForm.deId = ''

  if (contractFormRef.value) {
    contractFormRef.value.resetFields()
  }
}

// 处理对话框关闭
function handleDialogClose() {
  resetForm()
  emit('update:visible', false)
  emit('close')
}

// 处理对话框提交
function handleDialogSubmit() {
  contractFormRef.value.validate(async (valid) => {
    if (valid) {
      // 提交表单数据
      const formData = { ...contractForm }

      // 对于工程类合同，如果是编辑模式且有关联的子合同，不允许修改工程名称
      if (
        isEditMode.value &&
        currentContract.value?.crType === 1 &&
        currentContract.value?.children &&
        currentContract.value.children.length > 0
      ) {
        formData.projectName = currentContract.value.projectName
      }

      // 如果是新建模式，调用新建接口
      if (!isEditMode.value) {
        try {
          // 工程类合同，调用新建接口
          if (formData.crType === 1) {
            const res = await submitCreateContract(formData)
            if (res.code === 200) {
              ElMessage.success('创建成功')
              // 提交数据给父组件处理（用于刷新列表等）
              emit('submit', formData)
              // 关闭对话框
              handleDialogClose()
            } else {
              ElMessage.error(res.msg || '创建失败')
            }
          } else if (formData.crType === 2) {
            // 直销类合同，提交数据给父组件处理（跳转到配置页面）
            emit('submit', formData)
            // 关闭对话框
            handleDialogClose()
          }
        } catch (error) {
          console.error('创建合同失败:', error)
          ElMessage.error('创建合同失败')
        }
      } else {
        // 编辑模式，提交数据给父组件处理
        emit('submit', formData)
        // 关闭对话框
        handleDialogClose()
      }
    }
  })
}
</script>

<style scoped>
.dialog-form {
  margin-top: 20px;
}

.custom-descriptions {
  margin-bottom: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
/* 弹窗表单样式 */
.custom-descriptions {
  width: 100%;
}

.custom-descriptions .el-descriptions__item {
  display: flex;
  border-bottom: 1px solid #ebeef5;
}

.custom-descriptions .el-descriptions__label {
  width: 120px;
  font-weight: 500;
  color: #606266;
  text-align: center;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.custom-descriptions .el-descriptions__content {
  flex: 1;
  color: #303133;
  display: flex;
  align-items: center;
  padding: 18px 10px 0 10px !important;
}

.custom-descriptions .el-descriptions__row:last-child .el-descriptions__item {
  border-bottom: none;
}

.el-descriptions__cell--label {
  background-color: transparent !important;
}
:deep(.custom-descriptions .el-descriptions__cell) {
  padding: 0px 11px !important;
}
.el-form-item {
  margin-bottom: 16px;
}

/* 必填项星号样式 */
.required-label::before {
  content: '*';
  color: var(--el-color-danger);
  margin-right: 4px;
}
</style>
